//
//  DicOperation.swift
//  swiftStudy
//
//  Created by unisedu on 16/4/1.
//  Copyright © 2016年 CaoFei. All rights reserved.
//

import UIKit
/*
本讲主要介绍Dictionary的基本用法，主要内容包括
1. 字典的创建和初始化
2. 创建空的字典
3. 添加、修改和删除字典中的数据
4. 根据key获取value
5. 将value转换为特定的类型
6. 枚举字典中的key和value
7. 将key和value转换为数组
*/
class DicOperation: NSObject {
    func show(){
        
        //key 和value 必须固定类型
        //元素默认排序顺序一般按字母
        let employee1:Dictionary<String,String> = ["name":"bill","company":"Microsoft"]
        print(employee1)
        
        //不指定类型
        //实际上元素类型可以不同
        //整数不变
        var employee2 = ["name":"John","company":"Oracle","age":32]
        print(employee2)
        
        //浮点数会变成字符串
        let dict1 = ["product_name":"ice cream","price":5.5]
        print(dict1)
        
        //创建一个空字典
        var dict = Dictionary<Int,String>()
        
        dict[20] = "hello world"
        
        
        print(dict)
        
        //清空字典
        dict=[:]
        
        dict[21] = "abcd"
        dict[20] = "xyz"
        
        print(dict)
        
        if  let oldValue = dict.updateValue("飞机", forKey:21)
        {
            print("旧的值是\(oldValue)")
        }
        
        print(dict)
        print(dict.count)
        
        //as转换类型
        let age1:Int = employee2["age"] as! Int
        print(age1)
        
        if let age2:Int? = (employee2["age"] as? Int)
        {
            print(age2)
        }
        else
        {
            print("在字典中不存在这个key")
        }
        
        //删除 key 同时value也被删除了
        dict[20] = nil
        
        let oldValue1 = dict.removeValueForKey(21)
        print(oldValue1)
        
        
        //枚举字典中的key和value
        for(key,value) in employee1
        {
            print("\(key):\(value)")
        }
        
        
        for key in employee1.keys
        {
            print(key)
        }
        //隐式字典写法
        for key in (employee2 as Dictionary).keys
        {
            print(key)
        }
        
        for value in employee1.values
        {
            print(value)
        }
        dict[22]="abc"
        let keys = Array(dict.keys)
        print(keys)
        let value = Array(dict.values)
        print(value)

    }
}
